package com.example.myapplication;

import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Repository for managing blocked topics
 */
public class TopicRepository {

    private static final String PREFS_NAME = "blocked_topic_prefs";
    private static final String KEY_BLOCKED_TOPICS = "blocked_topics";

    private final SharedPreferences sharedPreferences;
    private final Gson gson;

    public TopicRepository(Context context) {
        this.sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        this.gson = new Gson();
    }

    /**
     * 获取所有禁用话题
     */
    public List<BlockedTopic> getAllTopics() {
        String json = sharedPreferences.getString(KEY_BLOCKED_TOPICS, null);
        if (json == null) {
            return new ArrayList<>();
        }
        Type listType = new TypeToken<ArrayList<BlockedTopic>>() {}.getType();
        return gson.fromJson(json, listType);
    }

    /**
     * 保存所有禁用话题
     */
    public void saveAllTopics(List<BlockedTopic> topics) {
        String json = gson.toJson(topics);
        sharedPreferences.edit().putString(KEY_BLOCKED_TOPICS, json).apply();
    }

    /**
     * 添加话题
     */
    public void addTopic(BlockedTopic topic) {
        List<BlockedTopic> topics = getAllTopics();
        topics.add(topic);
        saveAllTopics(topics);
    }

    /**
     * 更新话题
     */
    public void updateTopic(BlockedTopic topic) {
        List<BlockedTopic> topics = getAllTopics();
        for (int i = 0; i < topics.size(); i++) {
            if (topics.get(i).getId().equals(topic.getId())) {
                topics.set(i, topic);
                break;
            }
        }
        saveAllTopics(topics);
    }

    /**
     * 删除话题
     */
    public void deleteTopic(String id) {
        List<BlockedTopic> topics = getAllTopics();
        topics.removeIf(topic -> topic.getId().equals(id));
        saveAllTopics(topics);
    }

    /**
     * 根据ID获取话题
     */
    public BlockedTopic getTopicById(String id) {
        List<BlockedTopic> topics = getAllTopics();
        for (BlockedTopic topic : topics) {
            if (topic.getId().equals(id)) {
                return topic;
            }
        }
        return null;
    }

    /**
     * 检查话题是否被禁用
     */
    public boolean isTopicBlocked(String topicName) {
        List<BlockedTopic> topics = getAllTopics();
        for (BlockedTopic topic : topics) {
            if (topic.isEnabled() && topic.getTopic().equals(topicName)) {
                return true;
            }
        }
        return false;
    }
}

